﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace WZ.Common
{
    /// <summary>
    /// 数据库表-Model实体映射功能
    /// <remarks>注意！！！实体中的属性名称必须和表列名相同，必须相同，不同你就2逼了</remarks>
    /// </summary>
    public sealed class ModelHelper
    {
        private ModelHelper() { ;}

        private const string exception_msg0 = "Model实体类中不包含任何属性成员";
        private const string exception_msg1 = "参数为空";
        private const string exception_msg2 = "为空或列集合中列个数为0";

        /// <summary>
        /// 填充实体
        /// </summary>
        /// <typeparam name="T">实体类类型</typeparam>
        /// <param name="row">行</param>
        /// <param name="columns">列集</param>
        /// <returns></returns>
        public static T FillModel<T>(DataRow row, DataColumnCollection columns) where T : new()
        {
            if (row == null) throw new ArgumentNullException();
            if (columns == null || columns.Count == 0) throw new ArgumentNullException(exception_msg2);
            PropertyInfo[] propertys = (typeof(T)).GetProperties();
            int len = propertys.Length;
            if (len == 0) throw new Exception(exception_msg0);
            T obj = new T();
            for (int i = 0; i < len; i++)
            {
                string columnName = propertys[i].Name;
                if (columns.Contains(columnName))
                {
                    if (row[columnName] != DBNull.Value)
                    {
                        propertys[i].SetValue(obj
                            , Convert.ChangeType(row[columnName], propertys[i].PropertyType)
                            , null);
                    }
                }
            }
            return obj;
        }

        /// <summary>
        /// 填充实体集合
        /// </summary>
        /// <typeparam name="T">实体类类型</typeparam>
        /// <param name="dt">表集</param>
        /// <returns></returns>
        public static List<T> FillModelsFromDataTable<T>(DataTable dt) where T : new()
        {
            List<T> models = null;
            if (dt == null) { models = new List<T>(); models.Add(new T()); return models; }
            DataRowCollection rows = dt.Rows;
            DataColumnCollection dcc = dt.Columns;
            models = new List<T>(rows.Count);
            foreach (DataRow dr in rows)
            {
                models.Add(FillModel<T>(dr, dcc));
            }

            return models;
        }

        /// <summary>
        /// 防止数据绑定字段值为空的情况
        /// </summary>
        /// <param name="value">绑定值</param>
        /// <returns></returns>
        public static string DefendDBNull(object value, string insteadStr)
        {
            return (value == null || value == DBNull.Value)
                ? (string.IsNullOrEmpty(insteadStr) ? string.Empty : insteadStr)
                : value.ToString();
        }
    }
}
